package com.bluezone.dec.common.aspect;

import com.alibaba.fastjson.JSON;
import com.bluezone.dec.common.annotation.Log;
import com.bluezone.dec.system.entity.LogDO;
import com.bluezone.dec.system.service.LogService;
import com.bluezone.dec.utils.HttpContextUtils;
import com.bluezone.dec.utils.UUIDUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;

@Aspect
@Component
public class LogAspect {

    private static final Logger log = LoggerFactory.getLogger(LogAspect.class);

    @Autowired
    private LogService logService;

    /**
     * 切点
     */
    @Pointcut("@annotation(com.bluezone.dec.common.annotation.Log)")
    public void logPointCut() {
        throw new UnsupportedOperationException();
    }

    @Around("logPointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        long beginTime = System.currentTimeMillis();
        // 执行方法
        Object result = point.proceed();
        // 执行时长(毫秒)
        long time = System.currentTimeMillis() - beginTime;
        //异步保存日志
        log.info(String.valueOf(time));
        saveLog(point);
        return result;
    }

    void saveLog(ProceedingJoinPoint joinPoint) {

        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();

        LogDO sysLog = new LogDO();
        sysLog.setId(UUIDUtils.randomUUID());

        Log syslog = method.getAnnotation(Log.class);

        if (syslog != null) {
            // 注解上的描述
            sysLog.setOperation(syslog.value());
        }

        // 请求的方法名
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = signature.getName();
        sysLog.setMethod(className + "." + methodName + "()");

        // 请求的参数
        Object[] args = joinPoint.getArgs();
        try {
            String params = JSON.toJSONString(args[0]).substring(0, 4999);
            sysLog.setParams(params);
        } catch (Exception e) {
            log.warn("参数转换失败", e);
        }

        // 获取request
        HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
        // 设置IP地址
        sysLog.setIp(HttpContextUtils.getIpAddr(request));

        // 用户名
        // 系统当前时间
        Date date = new Date();
        sysLog.setGmtCreate(date);

        // 保存系统日志
        try {
            logService.save(sysLog);
        } catch (Exception e) {
            log.warn("日志保存失败", e);
        }
    }
}
